package own.stu.jobgib.playown.util.runShell;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import own.stu.jobgib.playown.vediodown.RuntimeUtil;
import own.stu.jobgib.playown.vediodown.bili.service.DownloadService;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

import static own.stu.jobgib.playown.vediodown.bili.service.DownloadService.getMessage;

/**
 * call shell
 * more see own.stu.jobgib.playown.vediodown.bili.service.BaseDownloadService
 */
public class YtDlp {

    private static Logger logger = LoggerFactory.getLogger(YtDlp.class);

    public static void main(String[] args) {
        try {
            // Process process = Runtime.getRuntime().exec("ls /Users/qim/Desktop/eng");
            //Process process = Runtime.getRuntime().exec("wget -O 1.jpg http://i1.hdslb.com/bfs/archive/478683435df15dd3cbf1358cd881d5e59ad68db2.jpg");

//            Process process = Runtime.getRuntime().exec("curl http://i1.hdslb.com/bfs/archive/478683435df15dd3cbf1358cd881d5e59ad68db2.jpg");
            //Process process = Runtime.getRuntime().exec("yt-dlp --cookies-from-browser chrome:/Users/qim/Library/Application\\ Support/Google/Chrome/Default https://b23.tv/BV1sg4y147pv");

           /* Process process = RuntimeUtil.exec("cd /Users/qim/Desktop/eng", "yt-dlp --cookies-from-browser chrome:/Users/qim/Library/Application\\ Support/Google/Chrome/Default https://b23.tv/BV1sg4y147pv");
            BufferedReader reader=new BufferedReader(new InputStreamReader(
                    process.getInputStream()));
            String line;
            while((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();*/

            // test_1();
            // test_3();
//            test_3_1();
//            test_3_2();

            test_4_multiThread();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void test_2() {
        List<String> result = RuntimeUtil.execForLines("cd /Users/qim/Desktop/eng", " yt-dlp --cookies-from-browser chrome:/Users/qim/Library/Application\\ Support/Google/Chrome/Default https://b23.tv/BV1sg4y147pv");
        System.out.println(result);
    }

    private static void test_1() {
        try {
            // ProcessBuilder processBuilder = new ProcessBuilder("sh", "/Users/qim/Documents/idea-code/play-own/src/main/java/own/stu/jobgib/playown/vediodown/script.sh");
            ProcessBuilder processBuilder = new ProcessBuilder();
            processBuilder.command("sh",
                    //"/Users/qim/Documents/idea-code/play-own/src/main/java/own/stu/jobgib/playown/vediodown/script.sh",
                    "/Users/qim/Documents/idea-code/play-own/src/main/java/own/stu/jobgib/playown/vediodown/cover_script.sh",
                    "BV1sg4y147pv");
            Process process = processBuilder.start();

            // 获取Shell脚本输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            process.waitFor();
            int exitValue = process.exitValue();
            if (exitValue != 0) {
                System.out.println(exitValue);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void test_3() {
        try {
            // ProcessBuilder processBuilder = new ProcessBuilder("sh", "/Users/qim/Documents/idea-code/play-own/src/main/java/own/stu/jobgib/playown/vediodown/script.sh");
            ProcessBuilder processBuilder = new ProcessBuilder();
            processBuilder.command("sh",
                    "/Users/qim/Documents/idea-code/play-own/src/main/java/own/stu/jobgib/playown/vediodown/cover_script.sh",
                    "/Users/qim/Desktop/eng",
                    "1-fjwe九佛额.jpg",
                    "http://i0.hdslb.com/bfs/archive/ddd7c0ef31d55305fd21959f6f6ae22279bd6bc4.jpg"
            );
            Process process = processBuilder.start();

            // 获取Shell脚本输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            process.waitFor(1, TimeUnit.MINUTES);
            int exitValue = process.exitValue();
            if (exitValue != 0) {
                logger.error("errorCode: {}, \n errMsg: {}", exitValue, getMessage(process.getErrorStream()));
            } else {
                logger.info("exitValue: {}", exitValue);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private static void test_3_1() {
        try {
            // ProcessBuilder processBuilder = new ProcessBuilder("sh", "/Users/qim/Documents/idea-code/play-own/src/main/java/own/stu/jobgib/playown/vediodown/script.sh");
            ProcessBuilder processBuilder = new ProcessBuilder();

           /*
           not ok
           processBuilder.command(
                    "cd",
                    "/Users/qim/Desktop/eng",
                    "wget",
                    "-O",
                    "1-fjwe九 佛额.jpg",
                    "http://i0.hdslb.com/bfs/archive/ddd7c0ef31d55305fd21959f6f6ae22279bd6bc4.jpg"
            );*/

            /*
            ok
            processBuilder.command("wget",
                    "-O",
                    "1-fjwe九 佛额.jpg",
                    "http://i0.hdslb.com/bfs/archive/ddd7c0ef31d55305fd21959f6f6ae22279bd6bc4.jpg"
            );*/

            processBuilder.command("yt-dlp",
                    "-P /Users/qim/Desktop/eng",
                    "-o 1xx.mp4",
                    "--cookies-from-browser",
                    "chrome:/Users/qim/Library/Application Support/Google/Chrome/Default",
                    "https://b23.tv/BV1sg4y147pv"
            );
            Process process = processBuilder.start();

            // 获取Shell脚本输出
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            process.waitFor(1, TimeUnit.MINUTES);
            int exitValue = process.exitValue();
            if (exitValue != 0) {
                logger.error("errorCode: {}, \n errMsg: {}", exitValue, getMessage(process.getErrorStream()));
            } else {
                logger.info("exitValue: {}", exitValue);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    // 不给力 RuntimeUtil  工具类，只能作参考
    private static void test_3_2() {
        try {

            List<String> strings = RuntimeUtil.execForLines(//"cd /Users/qim/Desktop/eng",
                    // "wget -O '1-fjwe九 佛额.jpg' http://i0.hdslb.com/bfs/archive/ddd7c0ef31d55305fd21959f6f6ae22279bd6bc4.jpg"
                    "wget -O \"1-fjwe九 佛额.jpg\" http://i0.hdslb.com/bfs/archive/ddd7c0ef31d55305fd21959f6f6ae22279bd6bc4.jpg"
            );
            System.out.println(strings);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void test_4_multiThread() throws InterruptedException, IOException {
        ExecutorService threadPool = Executors.newFixedThreadPool(2);
        String path = "/Users/qim/Desktop/idea-tmp";
        int cnt = 10;
        CountDownLatch latch = new CountDownLatch(cnt);
        AtomicInteger idx = new AtomicInteger();
        for (int i = 0; i < cnt; i++) {
            threadPool.execute(() -> {
                DownloadService.process("wget", "-O", path + "/" + idx.getAndIncrement() + ".jpg",
                        "http://i0.hdslb.com/bfs/archive/ddd7c0ef31d55305fd21959f6f6ae22279bd6bc4.jpg");

                latch.countDown();
            });
        }
        latch.await();
        System.out.println(" ---- done  -- -");
        threadPool.shutdown();
    }

}
